package org.ziegler.log.analysis.fileFilter;

import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.ziegler.log.analysis.AppConfig;
import org.ziegler.log.analysis.LogCore;
import org.ziegler.log.analysis.core.FileUtils;

public class DateFilterFilter implements FileFilter {

    private final List<File> recentFiles;

    public DateFilterFilter(LocalDateTime afterDateTime) {
        LogCore.debug("根据日期时间过滤文件 = " + afterDateTime.toString());

        final File[] files = FileUtils.listLogFiles(AppConfig.getInstance().getLogPath());

        recentFiles = Arrays.stream(files).filter(file -> {
            final LocalDateTime fileDateTime = LocalDateTime.ofEpochSecond(file.lastModified() / 1000,
                    0, ZoneOffset.ofHours(8));
            return fileDateTime.isAfter(afterDateTime);
        }).collect(Collectors.toList());
    }

    public static LocalDateTime toDateTime(String str) {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 2020-7-17 10:30:20
//        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        try {
            return LocalDateTime.parse(str, formatter);
        } catch (Exception e) {
            //System.out.println("解析时间数据异常 = " + str);
            return LocalDateTime.MAX;
        }
    }

    @Override
    public List<File> getFiles() {
        return recentFiles;
    }
}
